package com.zzyl.intercept;

import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.UserVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class UserTokenInterceptor implements HandlerInterceptor {


    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取header中的token
        String token = request.getHeader(Constants.USER_TOKEN);
        if(StringUtils.isEmpty(token)){
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        //解析token
        Claims claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);
        if(ObjectUtil.isEmpty(claims)){
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        //获取用户数据
        String userJson = String.valueOf(claims.get("user"));
        UserVo userVo = JSONUtil.toBean(userJson, UserVo.class);
        //获取redis中的用户对应的资源列表数据
        String urlListJson = redisTemplate.opsForValue().get(CacheConstants.PUBLIC_ACCESS_URLS + userVo.getId());
        List<String> urlList = null;
        if(!StringUtils.isEmpty(urlListJson)){
            urlList = JSONUtil.toList(urlListJson, String.class);
        }
        //验证用户是否拥有该访问的资源权限
        //获取当前请求的路径
        String targetUrl = request.getMethod()+request.getRequestURI();

        //测试环境下，临时放行所有请求
        /*for (String url : urlList) {
            if(antPathMatcher.match(url,targetUrl)){
                //把数据用户存储到threadlocal中
                UserThreadLocal.setSubject(userJson);
                return true;
            }
        }
        //没有权限，返回403
        throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);*/


        UserThreadLocal.setSubject(userJson);
        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.removeSubject();
    }
}
